package fr.cephb.locustree;



import com.sleepycat.bind.tuple.TupleInput;
import com.sleepycat.bind.tuple.TupleOutput;


import fr.cephb.berkeleydb.binding.XTupleBinding;
import fr.cephb.json.JSONBuilder;


/**
 * MappedObject
 * @author lindenb
 *
 */
public class MappedObject
	extends WithMetadata
	 {
	 private static final long serialVersionUID = 1L;
	 private String id;
	 private String name;
	 private int start;
	 private int end;

	 /**
	  * Binding for MappedObject
	  *
	  */
	 public static class Binding
	 	extends XTupleBinding<MappedObject>
		 {
		
		 public Binding()
			 {
			 
			 }
		 @Override
		public MappedObject entryToObject(TupleInput in)
			{
			MappedObject o= new MappedObject(
				in.readString(),
				in.readString(),
				in.readInt(),
				in.readInt()
				);
			o.setMetaData(this.readBytes(in));
			return o;
			}
		 @Override
		public void objectToEntry(MappedObject o, TupleOutput out)
			{
			out.writeString(o.getId());
			out.writeString(o.getName());
			out.writeInt(o.getStart());
			out.writeInt(o.getEnd());
			writeBytes(o.getMetaData(), out);
			}
		 
		 }
	 
	 
	 public MappedObject(String id,String name,int start,int end)
		 {
		 if(id==null) throw new NullPointerException();
		 if(start>end) throw new IllegalArgumentException();
		 this.id=id;
		 this.name=name;
		 if(this.name==null || this.name.length()==0) this.name=id;
		 this.start=start;
		 this.end=end;
		 }
	 
	 public String getId()
		{
		return id;
		}
	 public String getName()
		{
		return name;
		}
	 public int getStart()
		{
		return start;
		}
	 public int getEnd()
		{
		return end;
		}
	 
	 public int size()
			{
			return end-start;
			}
	 
	 
	 @Override
	public int hashCode()
		{
		final int prime = 31;
		int result = 1;
		result = prime * result + end;
		result = prime * result + id.hashCode();
		result = prime * result + name.hashCode();
		result = prime * result + start;
		return result;
		}

	@Override
	public boolean equals(Object obj)
		{
		if (this == obj) return true;
		if (obj == null) return false;
		if (getClass() != obj.getClass()) return false;
		MappedObject other = (MappedObject) obj;
		if (end != other.end) return false;
		if (start != other.start) return false;
		if (!id.equals(other.id)) return false;
		if (!name.equals(other.name)) return false;
		return true;
		}

	@Override
	public String toJSON()
		{
		return new JSONBuilder().
			put("name", getName()).
			put("id", getId()).
			put("start", getStart()).
			put("end", getEnd()).
			put("size", size()).
			put("properties", getJSON())
			.getString();
		}
	
	 @Override
	public String toString()
		{
		return toJSON();
		}
	}
